package com.yonyou.pmclouds.plan.processor;

import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.plan.entity.PlanProgressVO;
import com.yonyou.pmclouds.plan.entity.ScheduleItemVO;
import com.yonyou.pmclouds.plan.entity.ScheduleVO;
import com.yonyou.pmclouds.plan.rmiitf.IScheduleItemProcessor;
import com.yonyou.pmclouds.plan.utils.ScheduleDateCalculateUtil;
import com.yonyou.pmclouds.plan.utils.ScheduleProgressCalculateUtil;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Date;

/**
 *
 * @Description: 根据子级计算父级节点进度百分比
 * @Author: zhangzhonghao
 * @Date: 2020-03-06
 */
@Component
public class ScheduleSetParentProgressProcessor implements IScheduleItemProcessor {

    @Override
    public void process(ScheduleVO scheduleVO, ScheduleItemVO rootParentItemVO, ScheduleItemVO parentItemVO,
                        ScheduleItemVO childItemVO) throws BusinessException {
        if(childItemVO.getChildren() != null &&childItemVO.getChildren().length > 0){

            // 计算父级进度百分比
            computedParentProgress(childItemVO);

            // 推算父级实际开始、结束时间
            setStartAndEndDate(childItemVO);
        }

        // 判断该任务是否延期
        isDelay(childItemVO);
    }

    /**
     * 由子级计算父级节点的实际开始、结束时间
     * @param itemVO 当前节点
     */
    private void setStartAndEndDate(ScheduleItemVO itemVO) {
        ScheduleDateCalculateUtil.calculateParentDate(itemVO);
    }

    private void isDelay(ScheduleItemVO itemVO){
        boolean isDelay = false;
        Date currentDate = Calendar.getInstance().getTime();
        Date planEndDate = itemVO.getPlanEndDate();
        PlanProgressVO progressVO = itemVO.getProgressVO();

        if(progressVO != null){
            Date endDate = progressVO.getEndDate();

            // 超期条件：1. 无实际时间，则判断当前时间是否晚于计划结束时间 2. 有实际结束时间，则判断实际结束时间是否晚于计划结束时间
            if((endDate == null && currentDate.after(planEndDate)) || (endDate != null && endDate.after(planEndDate))){
                isDelay = true;
            }

        }else if(currentDate.after(planEndDate)){
            isDelay = true;
        }

        itemVO.setIsDelay(isDelay);
    }

    private void computedParentProgress(ScheduleItemVO parentItemVO) {
        ScheduleProgressCalculateUtil.calculateParentProgress(parentItemVO);

    }
}
